{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from dotenv import load_dotenv\n",
    "import os\n",
    "from pathlib import Path\n",
    "import json\n",
    "from openai import OpenAI, AsyncOpenAI\n",
    "from tqdm import tqdm\n",
    "import re\n",
    "from glob import glob\n",
    "from mistral_batch import MistralAIBatchProcessor\n",
    "from time import time\n",
    "import asyncio\n",
    "from asyncio import Semaphore\n",
    "from typing import List"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('survey_prompt.txt', 'r') as f:\n",
    "    survey_prompt = f.read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "load_dotenv(dotenv_path = '../APIS/.env')\n",
    "os.environ[\"XAI_API_KEY\"] = os.getenv('XAI_API_KEY')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = \"grok-2-latest\"\n",
    "client = OpenAI(api_key=os.getenv('XAI_API_KEY'), base_url=\"https://api.x.ai/v1\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "messages = [{\"role\": \"user\", \"content\": survey_prompt}]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "results = []\n",
    "n = 300\n",
    "for idx in tqdm(range(0, n), total = n):\n",
    "   \n",
    "    response = client.chat.completions.create(\n",
    "        model = \"grok-2-latest\",\n",
    "        # model = 'deepseek-reasoner',\n",
    "        messages=[\n",
    "            {\"role\": \"user\", \"content\": survey_prompt},\n",
    "        ],\n",
    "        stream=False,\n",
    "        max_tokens=1300,\n",
    "    )\n",
    "\n",
    "    results.append(response.choices[0].message.content)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "len(results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "formatted_results = []\n",
    "for res in results:\n",
    "    # res = res.choices[0].message.content\n",
    "    match = re.search(r'```json\\n(.*)\\n```', res, re.DOTALL)\n",
    "\n",
    "    if match:\n",
    "        json_str = match.group(1)  # Extract matched JSON string\n",
    "        json_dict = json.loads(json_str)  # Convert to dictionary\n",
    "        formatted_results.append(json_dict)  # Output the dictionary\n",
    "    else:\n",
    "        print(\"No JSON found.\")\n",
    "        print(res)\n",
    "        formatted_results.append(json_dict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "file_name = 'results/xai_grok2_res_0311-3.json'\n",
    "\n",
    "with open(file_name, \"w\", encoding=\"utf-8\") as json_file:\n",
    "    json.dump(formatted_results, json_file, indent=4)\n",
    "\n",
    "print(\"JSON data saved to\", file_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "file_name = 'results/xai_grpk2_res_0310-2.json'\n",
    "\n",
    "with open(file_name, \"w\", encoding=\"utf-8\") as json_file:\n",
    "    json.dump(formatted_results, json_file, indent=4)\n",
    "\n",
    "print(\"JSON data saved to\", file_name)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
